import json,requests
import os
import time

from bs4 import BeautifulSoup

class Movies():
    def __init__(self,i):
        self.url = f'https://ssr3.scrape.center/page/{i}'
        self.comment_url = 'https://ssr3.scrape.center'
        self.headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

    def send_re(self,url):
        response = requests.get(url, headers=self.headers,auth=('admin', 'admin')).text
        return response

    def send_img(self,url):
        response = requests.get(url, headers=self.headers)
        return response


    def jiexi(self,result,page):
        soup = BeautifulSoup(result, 'html.parser')
        # 定位“电影”区域（根据网页结构，可能需要更新）
        now_playing_section = soup.find('div', {'class':'el-col el-col-18 el-col-offset-3'})

        movies = []

        # 遍历每部电影卡片
        for item in now_playing_section.find_all('div', {'class':"el-card item m-t is-hover-shadow"}):
            title_tag = item.get_text(strip=True)
            img = item.find('img', {'class':'cover'}).get('src')
            href  = item.find('a').get('href')
            new_url = self.comment_url + href
            print(new_url)
            new_soup = BeautifulSoup(self.send_re(new_url), 'html.parser')
            time.sleep(2)
            comment = new_soup.find('p').get_text(strip=True)

            img_result = self.send_img(img)

            with open(f'./img/{title_tag[0:6]}.jpg','wb') as f:
                f.write(img_result.content)
                print(f'已保存{img}')

            if title_tag:
                movies.append({
                    'page_title': f'第{page}页',
                    'title': title_tag,
                    'img': img,
                    'comment': comment
                })



        return movies

if __name__ == '__main__':
    for i in range(1,2):
        m = Movies(i)
        result = m.send_re(m.url)
        aa = m.jiexi(result,i)
        print(f'第{i}页结束')
        # 1. 读旧数据（若文件不存在则初始化为 []）
        if os.path.exists('result.json'):
            with open('result.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
        else:
            data = []

        if isinstance(data, list):
            data.extend(aa)
        else:
            data.append(aa)

        with open('result.json', 'w+', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        time.sleep(1)
        #
        # with open('result.json', 'w', encoding='utf-8') as f:
        #     json.dump(aa, f, ensure_ascii=False, indent=4)

    # print(aa)
